package com.park.controller;

import com.park.common.bean.PageBean;
import com.park.common.constant.IPlatformConstant;
import com.park.common.po.UserOperator;
import com.park.common.util.DateUtil;
import com.park.common.util.JsonUtils;
import com.park.common.util.PoiUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class BaseController {
	public static final String REQUEST_HEAD = "text/html; charset=UTF-8";
	
	public static final String APPLICATION_JSON = "application/json";
    
	public static final String CONTENT_TYPE_TEXT_JSON = "text/json";

	/** 
	 * 为AJAX往前端输出的方法
	 * 
	 * @param o
	 *            想要输出的对象
	 * @return 是否成功
	 */
	protected boolean AjaxJsonWrite(Object o, HttpServletResponse response) {
		return AjaxJsonWrite(o, false, response);
	}

	protected boolean AjaxJsonWrite(Object o, boolean println, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setContentType(REQUEST_HEAD);
			out = response.getWriter();
			String jsonStr = String.valueOf(o instanceof String || o instanceof Number || o instanceof Boolean ? o
					: o instanceof List<?> || o instanceof Set<?> || o instanceof Object[] ? JSONArray.fromObject(o)
							: JSONObject.fromObject(o));
			if (println)
				System.out.println("zhe json string is " + jsonStr);
			out.write(jsonStr);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("JSON\u683c\u5f0f\u5316\u5bf9\u8c61\u65f6\u9519\u8bef" + o.getClass().getName());
			return false;
		} finally {
			out.flush();
			out.close();
		}
	}
	
	protected boolean AjaxJsonWriteGson(Object o, boolean println, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			response.setContentType(REQUEST_HEAD);
			out = response.getWriter();
			String jsonStr = JsonUtils.toJsonDF(o);
			if (println)
				System.out.println("zhe json string is " + jsonStr);
			out.write(jsonStr);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("JSON\u683c\u5f0f\u5316\u5bf9\u8c61\u65f6\u9519\u8bef" + o.getClass().getName());
			return false;
		} finally {
			out.flush();
			out.close();
		}
	}
	
	protected <T> T getData(String json, Class<T> clazz) {
		return JsonUtils.fromJson(json, clazz);
	}
	
	protected String redirect(String path) {
        return new StringBuilder(UrlBasedViewResolver.REDIRECT_URL_PREFIX).append(path).toString();
    }

    protected String forward(String path) {
        return new StringBuilder(UrlBasedViewResolver.FORWARD_URL_PREFIX).append(path).toString();
    }

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    protected UserOperator getUserInfo() {
        UserOperator userInfo = getUserInfo(getRequest().getSession());
        return userInfo;
    }

    protected UserOperator getUserInfo(HttpSession session) {
        return (UserOperator) session.getAttribute(IPlatformConstant.LOGIN_USER_IN);
    }

	protected com.park.common.poo.UserOperator getUserInfo2() {
		com.park.common.poo.UserOperator userInfo = getUserInfo2(getRequest().getSession());
		return userInfo;
	}

	protected com.park.common.poo.UserOperator getUserInfo2(HttpSession session) {
		return (com.park.common.poo.UserOperator) session.getAttribute(IPlatformConstant.LOGIN_USER_IN);
	}
	
    protected void setPageInfo(Model model, PageBean pageBean){
    	model.addAttribute("list", pageBean.getList());
		model.addAttribute("count", pageBean.getCount());
		model.addAttribute("lastPage", pageBean.getTotalPage());
		model.addAttribute("currentPage", pageBean.getCurrentPage());
		model.addAttribute("pageSize", pageBean.getPageSize());
    }
    
    protected void outExcel(HttpServletResponse response, Workbook workbook, String excelName) throws IOException {
    	HttpServletRequest request = getRequest();
		response.setHeader("Content-Disposition", "attachment;" + PoiUtil.getEncodingFileName(excelName + DateUtil.dateToString(new Date(), DateUtil.YYYYMMDD) + IPlatformConstant.EXCEL_EXTENSION_X, request.getHeader("User-Agent")));
		response.setStatus(200);
		ServletOutputStream outputStream = response.getOutputStream();
		workbook.write(outputStream);
		workbook.close();
		outputStream.flush();
		outputStream.close();
	}
    
    protected String getStreamResult(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		InputStream in=request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len=in.read(buffer))!=-1){
			out.write(buffer, 0, len);
		}
		out.close();
		in.close();
		return new String(out.toByteArray(),"utf-8");
	}

	protected void clearUserOperatorCookie(HttpServletResponse response){
		String host = getRequest().getServerName();
		Cookie cookie = new Cookie(IPlatformConstant.COOKIE_NAME_IN, null);
		cookie.setDomain(host);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);

		cookie = new Cookie(IPlatformConstant.COOKIE_PWD_IN, null);
		cookie.setDomain(host);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		System.out.println("cookie delete");
	}

	protected void setUserOperatorCookie(String mobile, String pwd, HttpServletResponse response){
		String host = getRequest().getServerName();
		Cookie cookie = new Cookie(IPlatformConstant.COOKIE_NAME_IN, mobile); // 保存用户名到Cookie
		cookie.setPath("/");
		cookie.setDomain(host);
		cookie.setMaxAge(99999999);
		response.addCookie(cookie);
		// 保存密码到Cookie，注意需要加密一下
		cookie = new Cookie(IPlatformConstant.COOKIE_PWD_IN, pwd);
		cookie.setPath("/");
		cookie.setDomain(host);
		cookie.setMaxAge(99999999);
		response.addCookie(cookie);
	}

	protected com.park.common.poo.UserOperator getUserOperatorCookie(){
		String usernameCookie = null;
		String passwordCookie = null;
		Cookie[] cookies = getRequest().getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (IPlatformConstant.COOKIE_NAME_IN.equals(cookie.getName())) {
					usernameCookie = cookie.getValue(); // 得到cookie的用户名
				}
				if (IPlatformConstant.COOKIE_PWD_IN.equals(cookie.getName())) {
					passwordCookie = cookie.getValue(); // 得到cookie的密码
				}
			}
			if (usernameCookie != null && passwordCookie != null) { // 如果存在
				com.park.common.poo.UserOperator userOperator = new com.park.common.poo.UserOperator();
				userOperator.setOperatorMobile(usernameCookie);
				userOperator.setOperatorPwd(passwordCookie);
				return userOperator;
			}
		}
		return null;
	}
    
}
